package algorithm.dfa;

import java.util.*;

/**
 * @program: util
 * @description: DFA算法判断是不是敏感词
 * 缺点: 只能最大匹配
 *      checkWord 里的王八不是敏感词问题
 * @author: zhouliangliang
 * @create: 2019-07-12 16:51
 **/
public class DFA {

    private String [] sensitive = new String [] {
            "王八蛋",
            "王八羔子",
            "日本鬼子",
            "白狗子"
    };

    private String [] checkWord = new String [] {
            "王八",
            "王八蛋",
            "日本鬼子"
    };

    /**
     * @param
     * @return
     */
    public Map senWordMap(Set<String> set) {
        Map dest = new HashMap<String, String>(set.size());
        Map temp = dest;
        Iterator<String> iter = set.iterator();
        while (iter.hasNext()) {
            String str = iter.next();
            for(int i=0; i<str.length(); i++) {
                //获取字符
                char ch = str.charAt(i);
                //获取字符对应的map
                Map wordMap = (Map)temp.get(ch);
                if(wordMap != null) {
                    temp = wordMap;
                } else {
                    //没有到词的最后，isEnd = 0
                    Map newMap = new HashMap<String, String>();
                    temp.put(ch, newMap);
                    temp.put("isEnd", '0');
                    temp = newMap;
                }

                //到了词的最后 isEnd = 1
                if(i == str.length() -1) {
                    temp.put("isEnd", "1");
                }
            }
            temp = dest;
        }

        return dest;
    }

    public boolean isSensitiveWord(Set<String> checkSet, Map map) {
        Map temp = map;
        Iterator<String> iter = checkSet.iterator();
        while (iter.hasNext()) {
            String str = iter.next();
            int i = 0;
            for(; i<str.length(); i++) {
                char ch = str.charAt(i);
                Map wordMap = (Map)temp.get(ch);
                if(wordMap != null) {
                    if("1".equals(wordMap.get("isEnd"))) {
                        System.out.println(str + "是敏感词!");
                        break;
                    }
                    temp = wordMap;
                } else {
                    System.out.println(str + "不是敏感词!");
                    break;
                }
            }

            //判断是不是到了最后
            if(i == str.length()) {
                System.out.println(str + "不是敏感词!");
            }

            temp = map;
        }

        return false;
    }

    public void test() {
        Set set = new HashSet();
        set.addAll(Arrays.asList(sensitive));
        Map senMap = this.senWordMap(set);

        Set checkWordSet = new HashSet();
        checkWordSet.addAll(Arrays.asList(checkWord));
        this.isSensitiveWord(checkWordSet, senMap);
    }

    public static void main(String[] args) {

        new DFA().test();
    }

}
